<template>
  <div class="robot_search basic_info" style="padding: 0 10px 0">
    <div class="robot_search_input" style="width: 100%">
      <el-select :disabled='disabledSelect' v-model="robotId" style="margin-right: 10px" placeholder="请选择" @change="robotChange" :value-key="'robotType'">
        <el-option
          v-for="item in robotOptions"
          :key="item._id"
          :label="item.robot_name_new"
          :value="item._id"
        >
        </el-option>
      </el-select>
      <el-input
        size="small"
        icon="search"
        v-model.trim="kmSearchContent"
        @keyup.native.enter.stop="handlerClick"
        :on-icon-click.stop="handlerClick"
      >
      </el-input>
    </div>
    <div class="robot_search_result">
      <div class="result">
        <p class="remark">共{{ resultNum }}个结果</p>
        <div
          v-for="(item, index) in resultList"
          class="result_list"
          v-on:mouseover="mouseOverList($event)"
          v-on:mouseout="mouseOutList($event)"
        >
          <div class="kmtitle clearfix">
            <h4 v-html="item.title"></h4>
            <div class="operate">
              <span
                v-show="(item.contentText || item.content) && !showrobotselect"
                @click.stop="sendRobotSearch('send', item)"
                >{{ $t('sms.send') }}</span
              >
              <span
                v-show="(item.contentText || item.content) && !showrobotselect"
                @click.stop="sendRobotSearch('use', item)"
                >{{ $t('webchat.use') }}</span
              >
              <span>
                <el-popover
                  placement="top"
                  width="400"
                  trigger="click"
                  v-model="item.correctVisible"
                  @after-leave="correctContent = ''"
                >
                  <div style="font-size: 12px">{{ $t('public.note') }}</div>
                  <el-input
                    type="textarea"
                    :rows="4"
                    resize="none"
                    v-model.trim="correctContent"
                  >
                  </el-input>
                  <div class="correct-btn-box">
                    <el-button
                      class="correct-btn"
                      size="mini"
                      @click="correctCancel(item)"
                      >{{ $t('public.cancel') }}</el-button
                    >
                    <el-button
                      class="correct-btn"
                      size="mini"
                      type="primary"
                      @click="correctSubmit(item)"
                      >{{ $t('webchat.send') }}</el-button
                    >
                  </div>
                  <span slot="reference">纠错</span>
                </el-popover>
              </span>
            </div>
          </div>
          <div
            class="kmcontent km-text-hide"
            v-html="item.content ? item.content : item.contentText"
          ></div>
          <div
            class="kmcontent km-text-limit"
            style="-webkit-box-orient: vertical"
            v-html="item.content ? item.content : item.contentText"
          ></div>
          <div
            class="open-text"
            @click="changeFoldedStatus($event)"
            ds_attr="unfolded"
          >
            {{ $t('email.unfolded') }}
          </div>
        </div>
        <div v-show="loading" class="loading-footer">
          <div class="loader">
            <div class="loading-1">
              <i></i>
              <i></i>
              <i></i>
            </div>
          </div>
        </div>
        <div
          class="btn"
          v-show="!noMore && resultNum > 10"
          @click.stop="search(true)"
        >
          <i class="iconfont icon-shuaxin"
            ><span>{{ $t('public.loadMore') }}</span></i
          >
        </div>
      </div>
    </div>
  </div>
</template>
<script type="text/javascript">
import bus from '@/store/eventBus'
export default {
  props: {
    // 是否右上角入口
    showrobotselect: {
      type: Boolean,
      default: false
    }
  },
  data () {
    return {
      kmSearchContent: '',
      resultList: [],
      currentPage: 1,
      humanAssistAccept: true,
      correctContent: "",
      noMore: false,
      resultNum: 0,
      loading: false,
      page: 1,
      robotOptions: [],
      robotId: '',
      robotType: '',
      disabledSelect: false,
      searchinprogress: false //搜索是否进行中
    }
  },
  computed: {
    sessionId () {
      let arr = this.$route.path.split('/')
      return arr[4]
    },
    tabType () {
      let arr = this.$route.path.split('/')
      return arr[3]
    },
    webChatData () {
      //  会话的详细信息
      if (this.tabType === 'webchat_todo' && this.$store.state.webchat.current.webchat_todo.currentSession[this.sessionId]) {
        return this.$store.state.webchat.current.webchat_todo.currentSession[this.sessionId]
      } else {
        return {}
      }
    }
  },
  watch: {
    webChatData: {
      deep: true,
      handler: function(value){
        if (value) {
          this.setRobotList();
        }
      }
    }
  },
  methods: {
    handlerClick () {
      if (this.kmSearchContent) {
        this.search()
      } else {
        this.$message.error(this.$t('webchat.searchConNoEmpty'))
        return
      }
    },
    mouseOverList (event) {
      let pane = event.currentTarget
      if (pane) {
        let node = pane.getElementsByClassName('km-text-hide')[0]
        let child = pane.getElementsByClassName('open-text')[0]
        if (node.offsetHeight > 51) { // 大于3行时加上展开2字
          child.style.display = 'block'
        } else {
          child.style.display = 'none'
        }
      }
    },
    correctSubmit (data) {
      if (!this.correctContent) {
        return
      }
      let correctData = {
        robot: this.robotId || this.webChatData.robotAssistId,
        question: data.question,
        query: data.query,
        correct: this.correctContent,
        qa_id: data.questionId
      }
      this.$store.dispatch('agentCorrect', correctData).then((res) => {
        if (res.success) {
          this.$message.success(this.$t('public.submitSuccess'))
          this.correctCancel(data)
        }
      })
    },
    correctCancel (data) {
      data.correctVisible = false
      this.correctContent = ''
    },
    mouseOutList (event) {
      let pane = event.currentTarget
      if (pane) {
        let child = pane.getElementsByClassName('open-text')[0]
        child.style.display = 'none'
      }
    },
    search (isScroll) {
      if (this.searchinprogress) {
        return
      }
      this.searchinprogress = true
      if (!isScroll) {
        this.resultList = []
        this.page = 1
      } else {
        this.page += 1
      }
      let robotId = this.robotId || this.webChatData.robotAssistId;
      if (!robotId) {
        this.$message.error('未设置辅助机器人，请设置后再搜索')
      }
      let robotType = '';
      if (this.$store.state.webchat && this.$store.state.webchat.current && this.$store.state.webchat.current[this.tabType] && this.$store.state.webchat.current[this.tabType].currentSession && this.$store.state.webchat.current[this.tabType].currentSession[this.sessionId]) {
        robotType = this.$store.state.webchat.current[this.tabType].currentSession[this.sessionId].assistRobotType || ''
      }
      if (this.robotId && !this.disabledSelect) {
        robotType = this.robotType;
      }
      let data = {
        robot: robotId,
        requestText: this.kmSearchContent,
        page: this.page,
        platform: this.webChatData.platform || '',
        limit: 10,
        assistRobotType: robotType
      }
      this.loading = true
      this.$store.dispatch('searchM7AIRobot', data).then((rep) => {
        this.loading = false
        if (rep.success) {
          rep.data.list.forEach(item => {
            this.$set(item, "correctVisible", false)
            this.resultList.push(item)
          })
          this.resultNum = rep.data.count
          if (this.resultList.length < 10 || this.resultList.length === rep.data.count) {
            this.noMore = true
          } else {
            this.noMore = false
          }
          this.humanAssistAccept = true
        } else {
          this.resultList = []
        }
        this.searchinprogress = false
      })
    },
    changeFoldedStatus (event) { // 更改展开还是收起的状态
      let pane = event.currentTarget
      if (pane) {
        let flag = pane.getAttribute('ds_attr')
        let child = pane.previousSibling
        if (flag === 'unfolded') {
          child.style.display = 'block'
          pane.setAttribute('ds_attr', 'folded')
          pane.innerHTML = this.$t('email.folded')
        } else {
          child.style.display = '-webkit-box'
          pane.setAttribute('ds_attr', 'unfolded')
          pane.innerHTML = this.$t('email.unfolded')
        }
      }
    },
    sendRobotSearch (type, item) {
      // 座席采纳，每次搜索之后，只可以上传一次采纳
      bus.$emit('sendRobotSearch', type, item, this.humanAssistAccept)
      this.humanAssistAccept = false
    },
    robotChange (item) {
      // this.kmSearchContent = '';
      this.robotOptions.some((item) => {
        if(item._id === this.robotId) {
          this.robotType = item.robotType;
          return true;
        } 
      })
      this.handlerClick()
    },
    getRobotList () {
      this.$store.dispatch('queryM7AIRobot', {}).then((res2) => {
        if (res2 && res2.success && res2.data && res2.data.length > 0) {
          let aiRobot = res2.data
          let allRobot = []
          aiRobot.forEach((item1) => {
            if (item1.Id) {
              item1._id = item1.Id
              item1.robot_name_new = item1.Nick
              allRobot.push(item1)
            }
          })
          this.$set(this, 'robotOptions', allRobot);
          // this.robotOptions = allRobot
          if (this.kmSearchContent && this.robotId) {
            this.handlerClick()
          } else {
            this.resultList = []
            this.resultNum = 0
          }
        }
      })
    },
    setRobotList () {
      // 代表聊天右侧智能辅助入口
      if (!this.showrobotselect) {
        if (this.webChatData.robotAssistId) {
          this.disabledSelect = true;
          this.robotId = this.webChatData.robotAssistId;
        } else {
           this.robotId = '';
           this.disabledSelect = false;
        }
      }
      this.getRobotList();
    },
    setKmSearchContent(value){
      this.kmSearchContent = value;
      if (value) {
        this.search()
      }
    }
  },
  mounted () {
    this.setRobotList();
    bus.$on('fastSearchAI', (data) => {
      // 代表右上角智能辅助
      if (this.showrobotselect) {
        return
      }
      this.kmSearchContent = data.data
      if (data.data) {
        this.search()
      }
    })
  },
  beforeDestroy () {
    bus.$off('fastSearchAI')
  }
}
</script>
<style lang="stylus">
@import '../../../assets/common.styl'
.robot_search_input
  display flex
  align-items center
  padding-bottom 10px
  border-bottom 1px solid $cf-gray5
  color #ccc
.robot_search_result
  padding 10px 0 20px
  h4
    font-size 13px
    float left
    width 78%
    white-space nowrap
    overflow hidden
    text-overflow ellipsis
  .greyFont, .kmcontent
    color $cf-gray5
    word-break break-all
  .result_list
    padding 8px 5px
    position relative
    overflow hidden
    &:first-child
      background-color $list-active
    &:hover
      background-color $list-active
      cursor pointer
    .kmtitle
      height 20px
      line-height 20px
      .km-type
        font-size 14px
        float right
      .operate
        color $c-main
        position absolute
        top 8px
        right 2px
        height 20px
        line-height 20px
        background-color $list-active
        display none
        span
          margin-right 10px
          cursor pointer
    .km-text-hide
      z-index -1
      position absolute
      opacity 0
    .open-text
      position absolute
      bottom 5px
      right 6px
      padding 0 5px
      text-align center
      height 20px
      line-height 20px
      background-color $list-active
      cursor pointer
      color $c-main
      display none
  .result_list:hover .operate
    display block
.remark
  color #999
</style>
